package com.example.administrator.appstpremvpdemo.helper;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author Administrator
 * @Date 2017/12/20
 * @description 线程池辅助类
 * @function
 */

public class ThreadPoolHelper {

    private static final int CORE_POOL_SIZE = 5;//线程池中的核心线程数量
    private static final int MAXIMUM_POOL_SIZE = 128;//线程池中的最大线程数量

    //当线程池中的线程数量超过了corePoolSize时，它表示多余的空闲线程的存活时间，
    // 即：多余的空闲线程在超过keepAliveTime时间内没有任务的话则被销毁
    private static final int KEEP_ALIVE_TIME = 2;

    //参数TimeUnit则是KEEP_ALIVE_TIME的单位，这里定义为秒。TimeUnit.SECONDS

    //每个线程执行任务的队列大小，这里设置最多10个任务
    private static final BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(10);

    //全局的静态线程池实例，保证唯一性，持久性
    public static final ThreadPoolExecutor sThreadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,
            MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS, workQueue);

    public static void runOnThread(Runnable runnable) {
        if (runnable==null) {
            return;
        }
        sThreadPoolExecutor.execute(runnable);
    }
}
